package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.utils.RelativeDateFormat;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.vo.CommentVO;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.QuanZiVo;
import com.tanhua.server.vo.VisitorsVo;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @program: my-tanhua
 * @description: 这个地方我没看懂，service到dubbo-api的关系
 * @author: xuejingjing
 * @create: 2021-09-25 13:40
 **/

@Service
public class QuanZiService {

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private PicUploadService picUploadService;

    @Reference (version = "1.0.0")
    private VisitorsApi visitorsApi;


    public PageResult queryPublishList(Integer page, Integer pageSize) {

        //分析：通过dubbo中的服务查询用户的好友动态
        //通过mysql查询用户的信息，回写到结果对象中（QuanZiVo）

        PageResult pageResult = new PageResult();
        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);

        //校验token是否有效，这个是之前的写法，后台在拦截器中进行了判断，能进入到这个类，说明token ，user肯定是存在的，直接取出来即可。
//        User user = userService.queryUserByToken(token);
//        if(user == null){
//            return pageResult;
//        }

        User user = UserThreadLocal.get();

        //通过dubbo查询数据
        PageInfo<Publish> pageInfo = quanZiApi.queryPublishList(user.getId(), page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return pageResult;
        }

        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        records.forEach(publish -> {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));
            quanZiVoList.add(quanZiVo);
        });

        //查询用户信息
        //这是啥意思？
        List<Object> userId = CollUtil.getFieldValues(records, "userId");
//        根据用户id列表查询用户信息
        List<UserInfo> userInfoList = userInfoService.queryUserInfoByIdList(userId);
        for (QuanZiVo quanZiVo : quanZiVoList) {
//找到对应的用户信息
            for (UserInfo userInfo : userInfoList) {
                if(quanZiVo.getUserId().longValue() ==userInfo.getUserId().longValue()){
                    fillUserInfoToQuanZiVO(userInfo,quanZiVo);
                    break;
                }
            }
        }
        pageResult.setItems(quanZiVos);
        return pageResult;

    }


    //填充用户信息
    private void fillUserInfoToQuanZiVO(UserInfo userInfo,QuanZiVo quanZiVo){
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));
        quanZiVo.setCommentCount(0); //TODO 评论数
        quanZiVo.setDistance("1.2公⾥里里"); //TODO 距离
        quanZiVo.setHasLiked(0); //TODO 是否点赞（1是，0否）
        quanZiVo.setLikeCount(0); //TODO 点赞数
        quanZiVo.setHasLoved(0); //TODO 是否喜欢（1是，0否）
        quanZiVo.setLoveCount(0); //TODO 喜欢数
    }

    /**
     * 发布动态
     * @param textContent
     * @param location
     * @param latitude
     * @param longitude
     * @param multipartFile
     * @return
     */
    public String savePublish(String textContent,
                              String location,
                              String latitude,
                              String longitude,
                              MultipartFile[] multipartFile) {
        //查询当前的登录信息
        //没看懂
        User user = UserThreadLocal.get();

        Publish publish = new Publish();
        publish.setUserId(user.getId());
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setSeeType(1);

        List<String> picUrls = new ArrayList<>();
        //图片上传
        for (MultipartFile file : multipartFile) {
            PicUploadResult picUploadResult = this.picUploadService.upload(file);
            picUrls.add(picUploadResult.getName());
        }

        publish.setMedias(picUrls);
        return this.quanZiApi.savePublish(publish);
    }

    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        //分析：通过dubbo中的服务查询系统推荐动态
        //通过mysql查询用户的信息，回写到结果对象中（QuanZiVo）

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        //直接从ThreadLocal中获取对象
        User user = UserThreadLocal.get();

        //通过dubbo查询数据
        PageInfo<Publish> pageInfo = this.quanZiApi.queryRecommendPublishList(user.getId(), page, pageSize);
        List<Publish> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }
        pageResult.setItems(this.fillQuanZiVo(records));
        return pageResult;
    }
    /**
     * 填充用户信息
     *
     * @param userInfo
     * @param quanZiVo
     */
    private void fillUserInfoToQuanZiVo(UserInfo userInfo, QuanZiVo quanZiVo){
        BeanUtil.copyProperties(userInfo, quanZiVo, "id");
        quanZiVo.setGender(userInfo.getSex().name().toLowerCase());
        quanZiVo.setTags(StringUtils.split(userInfo.getTags(), ','));

        quanZiVo.setCommentCount(0); //TODO 评论数
        quanZiVo.setDistance("1.2公里"); //TODO 距离
        quanZiVo.setHasLiked(0); //TODO 是否点赞（1是，0否）
        Long likeCount = quanZiApi.queryLikeCount(quanZiVo.getId());
        quanZiVo.setLikeCount(likeCount.intValue()); //TODO 点赞数
        User user = UserThreadLocal.get();
        Boolean aBoolean = quanZiApi.queryUserIsLike(user.getId(), quanZiVo.getId());
        int result = (aBoolean == true)?1:0;
        quanZiVo.setHasLoved(result); //TODO 是否喜欢（1是，0否）
        quanZiVo.setLoveCount(0); //TODO 喜欢数
    }
    /**
     * 根据查询到的publish集合填充QuanZiVo对象
     *
     * @param records
     * @return
     */
    private List<QuanZiVo> fillQuanZiVo(List<Publish> records){
        List<QuanZiVo> quanZiVoList = new ArrayList<>();
        records.forEach(publish -> {
            QuanZiVo quanZiVo = new QuanZiVo();
            quanZiVo.setId(publish.getId().toHexString());
            quanZiVo.setTextContent(publish.getText());
            quanZiVo.setImageContent(publish.getMedias().toArray(new String[]{}));
            quanZiVo.setUserId(publish.getUserId());
            quanZiVo.setCreateDate(RelativeDateFormat.format(new Date(publish.getCreated())));

            quanZiVoList.add(quanZiVo);
        });
        //查询用户信息
        List<Object> userIds = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);
        for (QuanZiVo quanZiVo : quanZiVoList) {
            //找到对应的用户信息
            for (UserInfo userInfo : userInfoList) {
                if(quanZiVo.getUserId().longValue() == userInfo.getUserId().longValue()){
                    this.fillUserInfoToQuanZiVo(userInfo, quanZiVo);
                    break;
                }
            }
        }

        return quanZiVoList;
    }

    /**
     * 点赞操作
     * @param publishId
     * @return
     */
    public Long likeCount(String publishId) {

        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.likeComment(user.getId(), publishId);
         //点赞成功，就查询点赞数
        if(result){
            //查询点赞数
            return  quanZiApi.queryLikeCount(publishId);
        }
        //不能用这个方法return  quanZiApi.queryLikeCount(publishId);
}

    /**
     * 取消点赞
     * @return
     */
    public long disLikeCount(String publishId) {
        User user = UserThreadLocal.get();
        Boolean result = quanZiApi.disLikeComment(user.getId(), publishId);
        if(result){
            //查询点赞数
            return  quanZiApi.queryLikeCount(publishId);
        }
    }

    /**
     * 查询单条圈子动态
     * @param publishId
     * @return
     */
    public QuanZiVo queryById(String publishId) {
        Publish publish = quanZiApi.queryPublishById(publishId);
        if(null == publish){
             return null; //这样写只是让他报错空指针吗？
        }
        //根据查询到的publish集合填充到
      //对象转成集合 ,此方法是数组转化为集合
        List<Publish> publishes = Arrays.asList(publish);
        return  fillQuanZiVo(publishes).get(0);
    }


    //这个publishID指的是？
    public PageResult queryCommentList(String publishId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Comment> pageInfo = quanZiApi.queryCommentList(publishId, page, pageSize);
        List<Comment> records = pageInfo.getRecords();
        if(CollUtil.isEmpty(records)){
            return  pageResult;
        }
        //
        List<CommentVO> listCommentVo = new ArrayList<>();
        for (Comment record : records) {
              CommentVO commentVO = new CommentVO();
            //id都要传过来吗？
            commentVO.setId(record.getId().toHexString());
            //评论
            commentVO.setContent(record.getContent());
            //创建时间
            commentVO.setCreateDate(DateUtil.format(new Date(record.getCreated()),"HH:mm"));
            //是否点赞
            commentVO.setHasLiked( quanZiApi.queryUserIsLike(record.getUserId(),commentVO.getId())?1:0);
            commentVO.setLikeCount(quanZiApi.queryLikeCount(commentVO.getId()).intValue());

            UserInfo userInfo = userInfoService.queryUserInfoById(record.getUserId());
            commentVO.setAvatar(userInfo.getLogo());
            commentVO.setNickname(userInfo.getNickName());
            listCommentVo.add(commentVO);
        }
        pageResult.setItems(listCommentVo);
        return pageResult;
    }

    /**
     * 发表评论
     * @param publishId
     * @param content
     * @return
     */
    public Boolean saveComments(String publishId, String content) {
        User user = UserThreadLocal.get();
        return this.quanZiApi.saveComment(user.getId(), publishId, content);
    }

    /**
     * 查询自己的所有动态
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Publish> publishPageInfo = quanZiApi.queryAlbumList(userId, page, page);
        if(ObjectUtil.isEmpty(publishPageInfo)){
             return  pageResult;
        }

        List<Publish> records = publishPageInfo.getRecords();
        pageResult.setItems(records);
        return pageResult;

    }

    /**
     * 谁看过我  //抄的
     * @return
     */
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        List<Visitors> visitorsList = visitorsApi.queryMyVisitor(user.getId());
        if (CollUtil.isEmpty(visitorsList)) {
            return Collections.emptyList();
        }

        List<Object> userIds = CollUtil.getFieldValues(visitorsList, "visitorUserId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIds);

        List<VisitorsVo> visitorsVoList = new ArrayList<>();

        for (Visitors visitor : visitorsList) {
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equals(visitor.getVisitorUserId(), userInfo.getUserId())) {

                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitor.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }
        return visitorsVoList;
    }
}